package com.jzqf.bluetooth.server

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.jzqf.bluetooth.base.BaseActivity
import com.jzqf.bluetooth.databinding.ActivityServiceBinding
import com.jzqf.bluetooth.event.EventMessage
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 服务端
 */
class ServiceActivity : BaseActivity<ActivityServiceBinding>() {
    //socket方式的服务端
//    private var serverService: ServerService? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
//        serverService = ServerService()
//        serverService?.startServer()
    }

    override fun onStart() {
        super.onStart()
        mViewBinding.startServerBtn.setOnClickListener {
            val intent = Intent(this, BleService::class.java)
            intent.putExtra("number", mViewBinding.inputEt.text.toString().toInt())
            startService(intent)
        }
    }

    /**
     *
     * 判断某activity是否处于栈顶
     * @return  true在栈顶 false不在栈顶
     */
    private fun isActivityTop(cls: Class<*>, context: Context): Boolean {
        val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val name = manager.getRunningTasks(1)[0].topActivity!!.className
        return name == cls.name
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventReceiveMain(eventMessage: EventMessage) {
        setView(eventMessage.message)
    }

    private fun setView(string: String) {
        runOnUiThread {
            mViewBinding.resultTv.setText(string)
            if (string.contains("断开连接")) {
//                serverService?.close()
//                serverService?.startServer()
            }
        }
    }

    override fun getViewBinding(): ActivityServiceBinding {
        return ActivityServiceBinding.inflate(layoutInflater)
    }


}